const fs = require("fs");
const uuid = require("short-uuid");
const gcoord = require("gcoord");
const { chunk } = require("lodash");
const axios = require("axios");

~(async () => {
  const getID = () => uuid.generate();

  const csv = fs.readFileSync("result.csv").toString("utf-8");
  const arr = csv
    .split("\n")
    .filter(Boolean)
    .map((e) => e.split(","));
  // 管线点号,连接点号,特征,附属物,雨水口形式,材质,断面尺寸,流向,起点埋深,终点埋深,埋设方式,偏心井号,井深,井室高度,井直径,井盖规格,井盖材质,混接点编号,混接等级,混接水体描述,混接点位置,接入排水户名称,是否安装防坠网,探测时水深,排放口地址,受纳水体,是否倒虹管,淤积深度,道路名称,探测日期,检查井等级,所属水系,备注,姓名,点号,横坐标,纵坐标,地面高程,
  const head = arr.shift();

  const points = arr.map((row) => {
    // 点对象
    const point = {
      id: getID(),
      nodeName: row[0], // 节点名称
      nodeCoordinate: `${row[35]}, ${row[36]}, ${row[37]}`, // 坐标字符串
      lng: row[35], // 经度
      lat: row[36], // 纬度
      lnglat: row[37], // 高度
      nodeDescribe: "", // 节点描述
      groundElevation: row[37],
      rotationAngle: "", // 旋转角
      interfaceMode: row[2], // 接口方式
      drainageType: row[0].includes("WS") ? "1" : "2", // 排水类型
      wellNo: row[0], // 井编号
      // wellBottom: row[12], // 井底深
      // wellNeckHeight: row[13], // 井脖高度
      // wellCoverShape: row[15].includes('X'), // 井盖形状
      wellMaterialQuality: row[16], // 井盖材质
      wellCoverSize: row[15], // 井盖尺寸
      wellDiameter: row[14], // 井直径
      feature: row[2], // 接口方式 [新增]
      appendage: row[3], // 附属物 [新增]
      rainwaterMouthForm: row[4], // 雨水口形式 [新增]
      wellDepth: row[12], // 井深 [新增]
      wellChamberHeight: row[13], // 井室高度 [新增]
    };

    return point;
  });

  const lines = arr.flatMap((row) => {
    if (!row[1]) {
      return [];
    }

    const startPoint = points.find((e) => e.nodeName === row[0]);
    const endPoint = points.find((e) => e.nodeName === row[1]);
    if (!endPoint) {
      console.log(row);
    }

    return [
      {
        id: getID(),
        startNodeId: !Number(row[7]) ? startPoint.id : endPoint.id,
        endNodeId: Number(row[7]) ? startPoint.id : endPoint.id,
        pipeLineName: "",
        pipeLineType: row[0].includes("WS") ? "1" : "2", // 管线类型
        materialQuality: row[5], // 材质
        pipeDiameter: row[6], // 管径或断面尺寸
        burialMethod: row[10], // 埋设方式
        startDepth: row[8], // 起点埋深 [新增]
        endDepth: row[9], // 终点埋深 [新增]
        mixingNo: row[17], // 混接点编号 [新增]
        mixingLv: row[18], // 混接等级 [新增]
        mixingWaterDesc: row[19], // 混接水体描述 [新增]
        mixingCoordinate: row[20], // 混接点位置 [新增]
      },
    ];
  });

  const result84 = {
    pipeNodeList: points,
    pipeLineGwList: lines,
  };

  const pointsChunked = chunk(points, 3);

  const pipeNodeList = [];

  for (const chunkItem of pointsChunked) {
    const res = await Promise.all(
      chunkItem.map((row) => {
        try {
          const [lng, lat] = gcoord.transform(
            [row.lng, row.lat],
            gcoord.WGS84,
            gcoord.GCJ02
          );

          return axios(
            `https://restapi.amap.com/v3/geocode/regeo?key=60e9ff19b9d6869352b44995fc651b37&location=${lng},${lat}`
          )
            .then((res) => {
              if (!res?.data?.regeocode?.formatted_address) {
                console.log("get address error", res);
              }
              const nodeDescribe = res.data.regeocode.formatted_address
              return {
                ...row,
                lng,
                lat,
                nodeCoordinate: `${lng}, ${lat}, ${row.lnglat}`,
                nodeDescribe: Array.isArray(nodeDescribe) ? "" : nodeDescribe,
              };
            })
            .catch((error) => {
              console.log("fetch reuqest failed", error);
            });
        } catch (error) {
          console.log("error", error);
        }
      })
    );
    pipeNodeList.push(...res);
  }

  const result02 = {
    pipeNodeList: pipeNodeList,
    pipeLineGwList: lines,
  };

  fs.writeFileSync("result-84-info.json", JSON.stringify(result84, null, 2));
  fs.writeFileSync("result-02-info.json", JSON.stringify(result02, null, 2));
})();
